package com.stone.serverless.web;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.view.AbstractUrlBasedView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/1/21 18:08
 * @Version: 1.0.0
 */
public class ClassLoaderResourceView extends AbstractUrlBasedView {
    //private Resource resource;

    public ClassLoaderResourceView() {

    }

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

        String url = this.getUrl();
        if(url.endsWith(".html")){
            response.setContentType("text/html");
        }else if(url.endsWith(".js")){
            response.setContentType("text/javascript");
        }else if(url.endsWith(".css")){
            response.setContentType("text/css");
        }
        Object handler = model.get("handler");
        if (null != handler) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            InputStream resourceAsStream =null;
            if(url.endsWith(".html")){
                 resourceAsStream = handlerMethod.getBean().getClass().getResourceAsStream("/templates/"+this.getUrl());

            }else if(url.endsWith(".js")||url.endsWith(".css")){
                resourceAsStream = handlerMethod.getBean().getClass().getResourceAsStream("/static/"+this.getUrl());
            }

            if(ObjectUtil.isNotNull(resourceAsStream)){
                FileCopyUtils.copy(resourceAsStream, response.getOutputStream());
            }
        }

    }

}
